package com.company.workflow.service.impl;

import com.company.workflow.model.dto.AddSignDto;
import com.company.workflow.model.dto.DeleteSignDto;
import com.company.workflow.service.ProcessOperationService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProcessOperationServiceImpl implements ProcessOperationService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Override
    @Transactional
    public void recallProcess(String processInstanceId, String taskId) {
        // 获取当前任务
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .taskId(taskId)
                .singleResult();
        
        if (currentTask == null) {
            throw new RuntimeException("当前任务不存在");
        }

        // 获取上一个任务
        List<HistoricTaskInstance> historicTaskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .finished()
                .orderByTaskCreateTime().desc()
                .list();

        if (historicTaskList.isEmpty()) {
            throw new RuntimeException("没有可撤回的任务");
        }

        HistoricTaskInstance lastTask = historicTaskList.get(0);

        // 删除当前任务
        taskService.deleteTask(currentTask.getId());

        // 创建新任务（回退到上一个任务）
        Map<String, Object> variables = new HashMap<>();
        variables.put("processInstanceId", processInstanceId);
        taskService.complete(currentTask.getId(), variables);
        
        // 创建新任务并设置变量
        Task newTask = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        
        if (newTask != null) {
            taskService.setAssignee(newTask.getId(), lastTask.getAssignee());
            taskService.setVariable(newTask.getId(), "recalled", true);
        }
    }

    @Override
    @Transactional
    public void addSign(AddSignDto addSignDto) {
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(addSignDto.getProcessInstanceId())
                .taskId(addSignDto.getTaskId())
                .singleResult();

        if (currentTask == null) {
            throw new RuntimeException("当前任务不存在");
        }

        // 创建加签任务变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("assignee", addSignDto.getAssignee());
        variables.put("signType", addSignDto.getSignType());
        
        // 如果是前加签，当前任务需要等待加签任务完成
        if ("BEFORE".equals(addSignDto.getSignType())) {
            runtimeService.suspendProcessInstanceById(addSignDto.getProcessInstanceId());
        }
        
        // 创建加签任务
        taskService.complete(currentTask.getId(), variables);
    }

    @Override
    @Transactional
    public void deleteSign(DeleteSignDto deleteSignDto) {
        Task task = taskService.createTaskQuery()
                .processInstanceId(deleteSignDto.getProcessInstanceId())
                .taskId(deleteSignDto.getTaskId())
                .singleResult();

        if (task == null) {
            throw new RuntimeException("任务不存在");
        }

        // 删除任务
        Map<String, Object> variables = new HashMap<>();
        variables.put("deleteReason", deleteSignDto.getReason());
        taskService.complete(task.getId(), variables);

        // 激活被挂起的流程实例（如果有）
        runtimeService.activateProcessInstanceById(deleteSignDto.getProcessInstanceId());
    }
} 